package com.iotek.ssm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadController {

    @RequestMapping("/uploadImg")
    @ResponseBody
    public String uploadImage(
            @RequestParam(value = "image", required = true) MultipartFile file) {

        if (file.isEmpty()) {
            return "image is empty!!!";
        }

        // 保存到本地的虚拟映射路径下
        String savePath = "F:\\common files for java\\Itomcat文件缓存\\upload_images";
        String uuidName = UUID.randomUUID().toString();

        String originaFileName = file.getOriginalFilename();
        // 截取后缀名
        String suffix = originaFileName.substring(originaFileName.lastIndexOf(".") + 1, originaFileName.length());

        String newFileName = uuidName + "." + suffix;

        File imageFile = new File(savePath, newFileName);

        try {
            file.transferTo(imageFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "http://localhost:8080/imgMap/" + newFileName;
    }
}
